<?php

namespace mpend\modules\h5\models;

use mpend\models\User;
use common\exceptions\ModelHttpException;
use common\models\orange\OrangeShopGoods;
use common\models\orange\OrangeShopOrder;
use common\models\orange\OrangeShopOrderGoods;
use common\models\orange\OrangeShopOrderLog;
use common\models\orange\UserOrangeGoods;
use common\models\user\UserAccountOrange;
use common\models\user\UserAccountOrangeRecord;
use yii\db\Exception;

class OrangeOrderForm extends \common\base\Model {

    /**
     * @name $user_id
     * @var integer 用户UID
     */
    public $user_id;

    /**
     * @name $goods_id
     * @var integer 产品id
     */
    public $goods_id;

    /**
     * @name $goods_num
     * @var string 动态内容
     */
    public $goods_num;

    /**
     * @name $order_from
     * @var string  [ios,android]
     */
    public $order_from;

    /**
     * @name $ship_name
     * @var string  收货人名
     */
    public $ship_name;

    /**
     * @name $ship_mobile
     * @var string  收货人手机号
     */
    public $ship_mobile;

    /**
     * @name $order_from
     * @var string  收货省
     */
    public $ship_province;

    /**
     * @name $order_from
     * @var string  收货市
     */
    public $ship_city;

    /**
     * @name $order_from
     * @var string  收货区
     */
    public $ship_district;

    /**
     * @name $order_from
     * @var string  详情地址
     */
    public $ship_address;
    private $_goods;
    private $_user;

    public function rules() {
        return [
            [['user_id', 'goods_id', 'goods_num'], 'integer'],
            [['goods_id', 'goods_num', 'order_from', 'ship_name', 'ship_mobile', 'ship_province', 'ship_city', 'ship_district', 'ship_address'], 'required'],
            [['ship_name', 'ship_mobile', 'ship_province', 'ship_city', 'ship_district', 'ship_address'], 'required'],
            [['ship_name'], 'string', 'max' => '30'],
            [['ship_mobile'], 'string', 'max' => '11'],
            [['ship_province'], 'string', 'max' => '11', 'min' => '1'],
            [['ship_city'], 'string', 'max' => '30', 'min' => '1'],
            [['ship_district'], 'string', 'max' => '60', 'min' => '1'],
            [['ship_address'], 'string', 'max' => '120', 'min' => '1'],
            ['goods_num', 'validateStock'],
            ['order_from', 'in', 'range' => ['android', 'ios']]
        ];
    }

    /**
     * 校验库存
     */
    public function validateStock($attribute) {
        if (!$this->hasErrors()) {
            if ($this->$attribute < 1) {
                $this->addError($attribute, '下单产品数量不能小于1');
            }
            $this->$attribute;
            $goods = OrangeShopGoods::findOne($this->goods_id);

            $this->_goods = $goods;
            if (($goods->stock - $this->$attribute) < 0) {
                $this->addError($attribute, '商品库存不足,下单失败!');
            }
        }
    }

    /**
     * 创建订单
     * @param [type] $data
     * @return void
     */
    public function save() {
        if (!$this->validate()) {
            throw new ModelHttpException('订单创建失败', $this->getFirstErrors());
        }
        $model = new OrangeShopOrder();
        $transaction = \Yii::$app->db->beginTransaction();
        $user = User::findOne($this->user_id);
        $goods = $this->_goods;
        $costOrange = $goods->orange_price * $this->goods_num;
        $this->_user = $user;
        try {
            //生成订单
            $model->generateTn();
            $model->refreshTime($model::STATUS_DEFAULT);
            $model->ship_name = $this->ship_name;
            $model->ship_mobile = $this->ship_mobile;
            $model->ship_province = $this->ship_province;
            $model->ship_city = $this->ship_city;
            $model->ship_district = $this->ship_district;
            $model->ship_address = $this->ship_address;
            $model->is_express = $this->_goods->is_express;
            $model->status = $model::STATUS_SUCCESS;
            $model->pay_starttime = time();
            $model->pay_time = time();
            $model->user_id = $this->_user->id;
            $model->order_from = $this->order_from;
            $model->order_type = $this->_goods->goods_style;
            $model->goods_orange = $costOrange;
            if (!$model->save()) {
                throw new Exception('订单创建失败:' . implode(';', $model->firstErrors));
            }

            //减少库存
            if ($goods->status != OrangeShopGoods::STATUS_UP) {
                throw new Exception('商品未上架,不允许销售');
            }
            $goods->stock -= $this->goods_num;
            if (!$goods->save()) {
                throw new Exception('商品库存减少失败:' . implode(';', $goods->firstErrors));
            }

            //订单商品存储
            $orangeOrderGoods = new OrangeShopOrderGoods();
            $orangeOrderGoods->order_id = $model->id;
            $orangeOrderGoods->goods_id = $goods->id;
            $orangeOrderGoods->user_id = $this->_user->id;
            $orangeOrderGoods->goods_num = $this->goods_num;
            $orangeOrderGoods->goods_name = $goods->name;
            $orangeOrderGoods->goods_code = $goods->goods_code;
            $orangeOrderGoods->goods_type = $goods->goods_style;
            $orangeOrderGoods->orange_price = $goods->orange_price;
            $orangeOrderGoods->goods_image = $goods->cover;
            if (!$orangeOrderGoods->save()) {
                throw new Exception('订单商品存储失败:' . implode(';', $orangeOrderGoods->firstErrors));
            }

            //橙子
            $orange = $user->orange;
            if (!$orange) {
                throw new Exception('用户橙子账户不存在,无法兑换商品');
            }
            if ($orange->status == UserAccountOrange::STATUS_FORZEN) {
                throw new Exception('用户橙子账户被冻结,无法兑换');
            }
            if ($orange->status == UserAccountOrange::STATUS_NO_ACTIVE) {
                throw new Exception('用户橙子账户未激活,无法兑换');
            }


            if ($orange->current < $costOrange) {
                throw new Exception('用户橙子账户余额不足');
            }
            $orange->current -= $costOrange;
            if (!$orange->save()) {
                throw new Exception('橙子保存失败' . implode(';', $orange->firstErrors));
            }

            //订单商品领取
            $userOrangeGoods = new UserOrangeGoods();
            $userOrangeGoods->user_id = $this->_user->id;
            $userOrangeGoods->goods_id = $this->goods_id;
            $userOrangeGoods->goods_code = $goods->goods_code;
            $userOrangeGoods->goods_name = $goods->name;
            $userOrangeGoods->overtime = $goods->overtime;
            $userOrangeGoods->order_id = $model->id;
            $userOrangeGoods->order_sn = $model->order_no;
            $userOrangeGoods->save();

            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            \Yii::error($e->getMessage());
            throw new Exception($e->getMessage());
        }

        //橙子账户记录
        $this->orangeRecord($costOrange, $model->id);
        //订单日志记录
        $this->orderLog($model->id);

        return $model->attributes;
    }

    public function orderLog($orderId) {
        $model = new OrangeShopOrderLog();
        $model->saveLog(OrangeShopOrderLog::ACTION_CRAETE);
        $model->user_id = $this->_user->id;
        $model->order_id = $orderId;
        $model->is_show = 1;
        if (!$model->save()) {
            \Yii::error($model->firstErrors);
        }
    }

    /**
     * 记录橙子
     * @param $value
     * @param $orderId
     */
    public function orangeRecord($value, $orderId) {
        $record = new UserAccountOrangeRecord();
        $record->balance = $record::BALANCE_REDUCE;
        $record->user_id = $this->_user->id;
        $record->value = $value;
        $record->ip = '';
        $record->model = 'OrangeShopOrder';
        $record->model_id = $orderId;
        $record->save();
        if (!$record->save()) {
            \Yii::error($record->firstErrors);
        }
    }

}
